﻿using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.Practices.Unity;

namespace MyAMS.WebServer
{
    /// <summary>
    /// Mvc应用程序
    /// </summary>
    public class MvcApplication : HttpApplication, IWebServer
    {
        #region IWebServer Members

        /// <summary>
        /// 获取组件列表
        /// </summary>
        public IEnumerable<IComponent> Components
        {
            get { return Application["components"] as IEnumerable<IComponent>; }
        }

        /// <summary>
        /// 获取组件数量
        /// </summary>
        /// <value></value>
        public int ComponentCount
        {
            get { return Components.Count(); }
        }

        /// <summary>
        /// 获取模块管理器
        /// </summary>
        /// <value></value>
        public IModulesManager ModulesManager
        {
            get { return Components.FirstOrDefault(c => c is IModulesManager) as IModulesManager; }
        }


        /// <summary>
        /// 开始时被调用
        /// </summary>
        public virtual void OnStart()
        {
            Load(new HttpContextWrapper(Context), this);
        }

        /// <summary>
        /// 结束时被调用
        /// </summary>
        public virtual void OnEnd()
        {
            if (Context != null && Context.Application != null)
            {
                IEnumerable<IComponent> components = Context.Application["components"] as IEnumerable<IComponent>;
                foreach (IComponent component in components)
                {
                    component.Dispose();
                }
                Context.Application.Remove("components");
            }
        }

        #endregion

        /// <summary>
        /// 在应用程序开始时发生
        /// </summary>
        protected void Application_Start()
        {
            OnStart();
        }

        /// <summary>
        /// 在应用程序结束时发生
        /// </summary>
        protected void Application_End()
        {
            OnEnd();
        }

        private static void Load(HttpContextBase context, IApplication application)
        {
            if (!context.Application.AllKeys.Contains("container"))
            {
                context.Application.Add("container", ContainerFactory.Create());
            }
            IUnityContainer container = context.Application["container"] as IUnityContainer;

            IEnumerable<IComponent> components = container.ResolveAll<IComponent>();
            foreach (IComponent component in components)
            {
                if (!component.IsInitialized)
                {
                    component.Initialize(application);
                }
            }
            context.Application["components"] = components;
        }
    }
}
